package com.ch1.kafka001.commit;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;


//kafka-topics.bat --zookeeper localhost:2181 --create --topic topic1 --replication-factor 1 --partitions 4
public class ProducerCommit {
    private static KafkaProducer<String,String> producer = null;

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("bootstrap.servers","127.0.0.1:9092");
        props.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");

        producer = new KafkaProducer<String, String>(props);

        try{

            ProducerRecord<String,String> record;
            try{

                for(int  i=0;i<50;i++){
                    SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
                    Date date = new Date();
                    String d = format.format(date);
                    record = new ProducerRecord<String, String>("topic1","key"+i,"value"+i+"，时间："+d);
                    producer.send(record);
                    System.out.println("数据【"+record+"】已发送");
                }

            }catch (Exception e){
                e.printStackTrace();
            }

        }finally {
            producer.close();
        }
    }
}
